package com.make.house.api.controller.video;

import com.make.house.api.common.CommonParams;
import com.make.house.api.common.ECConstant;
import com.make.house.api.controller.BaseRequestParams;
import com.make.house.api.entity.video.VideoEntity;
import com.make.house.api.entity.video.VideoTypeEntity;
import com.make.house.api.model.ActionStatus;
import com.make.house.api.model.JSONResult;
import com.make.house.api.repository.video.VideoRepository;
import com.make.house.api.repository.video.VideoTypeRepository;
import com.make.house.api.utils.NumberUtils;
import com.make.house.api.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

/**
 * Created by yanglinlong on 18/8/22.
 */
@RestController
@RequestMapping(ECConstant.API_REQUEST_BASE_URL+"/video")
@Api("视频相关")
public class VideoController {

    @Autowired
    private VideoRepository videoRepository;

    @Autowired
    private VideoTypeRepository videoTypeRepository;

    @ApiOperation(value="视频详情", notes="获取视频详细", response = VideoEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "视频id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public JSONResult getVideoDetail(@ApiIgnore HttpServletRequest request){
        String obj = request.getParameter("id");
        int id = NumberUtils.toInt(obj, -1);
        if (id < 0){
            return JSONResult.newBuilder().setStatus(ActionStatus.PARAMAS_ERROR.inValue())
                    .setDesc("id error").build();
        }

        VideoEntity videoEntity = videoRepository.findById(id);
        if (videoEntity == null) {
            return JSONResult.NO_RESULT;
        }
        return JSONResult.okResult(videoEntity);
    }


    @ApiOperation(value="新增视频", notes="新增一个视频", response = VideoEntity.class)
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public JSONResult insertVideo(InsertVideoPara para){
       if (para == null){
           return JSONResult.paramErrorResult("para can not be null");
       }
       if (StringUtils.isEmpty(para.getName())){
           return JSONResult.paramErrorResult("name can not be null");
       }
       if (StringUtils.isEmpty(para.getDesc())){
           return JSONResult.paramErrorResult("desc can not be null");
       }
       if (StringUtils.isEmpty(para.getAuthor())){
           return JSONResult.paramErrorResult("author can not be null");
       }
       if (StringUtils.isEmpty(para.getUrl())){
           return JSONResult.paramErrorResult("video url can not be null");
       }
        if (StringUtils.isEmpty(para.getCover())){
            return JSONResult.paramErrorResult("video cover can not be null");
        }
       if (para.getTid() < 0){
           return JSONResult.paramErrorResult("please choose a type");
       }else {
           VideoTypeEntity videoTypeEntity = videoTypeRepository.findById(para.getTid());
           if (videoTypeEntity == null){
               return JSONResult.paramErrorResult("no such video type");
           }
       }
       if (para.getIsTry() == 1 && para.getTryDuration() < 0){
           return JSONResult.paramErrorResult("please input try duration");
       }
       if (para.getDuration() < 0){
           return JSONResult.paramErrorResult("please input video duration");
       }

       VideoEntity entity = new VideoEntity();
       entity.setTid(para.getTid());
       entity.setName(para.getName());
       entity.setDesc(para.getDesc());
       entity.setFrom(para.getFrom());
       entity.setUploadTime(System.currentTimeMillis());
       entity.setAuthor(para.getAuthor());
       entity.setPrice(para.getPrice());
       entity.setOriPrice(para.getOriPrice());
       entity.setIsTry(para.getIsTry());
       entity.setTryDuration(para.getTryDuration());
       entity.setUrl(para.getUrl());
       entity.setDuration(para.getDuration());
       entity.setIsFree(para.getIsFree());
       entity.setIsTop(para.getIsTop());
       entity.setCover(para.getCover());
       try {
           videoRepository.save(entity);
       }catch (Exception e){
           return JSONResult.newBuilder().setStatus(ActionStatus.DATABASE_ERROR.inValue())
                   .setDesc(ActionStatus.DATABASE_ERROR.getDescription()).build();
       }
       return JSONResult.okResult(entity);
    }


    @ApiOperation(value="视频分类详情", notes="获取视频分类详细", response = VideoEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tid", value = "视频分类id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/type/detail", method = RequestMethod.GET)
    public JSONResult getVideoTypeDetail(@ApiIgnore HttpServletRequest request){
        String obj = request.getParameter("tid");
        int id = NumberUtils.toInt(obj, -1);
        if (id < 0){
            return JSONResult.newBuilder().setStatus(ActionStatus.PARAMAS_ERROR.inValue())
                    .setDesc("tid error").build();
        }

        VideoTypeEntity videoEntity = videoTypeRepository.findById(id);
        if (videoEntity == null) {
            return JSONResult.NO_RESULT;
        }
        return JSONResult.okResult(videoEntity);
    }

    @ApiOperation(value="新增视频分类", notes="新增一个视频分类", response = VideoTypeEntity.class)
    @RequestMapping(value = "/type/insert", method = RequestMethod.POST)
    public JSONResult insertVideoType(InsertVideoTypePara para){
        if (para == null){
            return JSONResult.paramErrorResult("para can not be null");
        }
        if (StringUtils.isEmpty(para.getName())){
            return JSONResult.paramErrorResult("name can not be null");
        }
        if (StringUtils.isEmpty(para.getDesc())){
            return JSONResult.paramErrorResult("desc can not be null");
        }

        VideoTypeEntity entity = new VideoTypeEntity();
        entity.setName(para.getName());
        entity.setDesc(para.getDesc());
        entity.setIsTop(para.getIsTop());
        try {
            videoTypeRepository.save(entity);
        }catch (Exception e){
            return JSONResult.newBuilder().setStatus(ActionStatus.DATABASE_ERROR.inValue())
                    .setDesc(ActionStatus.DATABASE_ERROR.getDescription()).build();
        }
        return JSONResult.okResult(entity);
    }


    @ApiOperation(value = "获取首页视频列表", notes = "获取首页视频列表", response = VideoEntity.class)
    @RequestMapping(value = "/main/list", method = RequestMethod.GET)
    public JSONResult getVideoList(BaseRequestParams params){
        if (params == null){
            return JSONResult.paramErrorResult("para can not be null");
        }

        ArrayList<MainVideoListResponseList> responseLists = new ArrayList<MainVideoListResponseList>();

        ArrayList<VideoTypeEntity> videoTypeList = videoTypeRepository.findAllByOrderByIsTopDescIdAsc();
        if (videoTypeList != null){
            for (int i = 0; i < videoTypeList.size(); i++){
                VideoTypeEntity videoTypeEntity = videoTypeList.get(i);
                //过滤掉已经删除或者下架的视频
                if(CommonParams.VideoStauts.DELETE.equals(videoTypeEntity.getStatus())
                        || CommonParams.VideoStauts.SOLD_OUT.equals(videoTypeEntity.getStatus())){
                    continue;
                }
                ArrayList<VideoEntity> videoList = videoRepository.findByTidOrderByIsTopDescIdAsc(videoTypeList.get(i).getId());
                if (videoList != null && videoList.size() > 0){
                    //过滤掉已经删除的数据
                    removeVideo(videoList);
                    MainVideoListResponseList responseBean = new MainVideoListResponseList();
                    responseBean.setVideoType(videoTypeEntity);
                    if (videoList.size() > CommonParams.VIDEO_LIST_NUM){ //5个就显示更多
                        ArrayList<VideoEntity> temp = new ArrayList<VideoEntity>();
                        temp.addAll(videoList.subList(0, CommonParams.VIDEO_LIST_NUM - 1));
                        responseBean.setVideoList(temp);
                        responseBean.setHasMore(1);
                    }else {
                        responseBean.setVideoList(videoList);
                        responseBean.setHasMore(0);
                    }
                    responseLists.add(responseBean);
                }
            }
        }

        return JSONResult.okResult(responseLists);
    }

    @ApiOperation(value="获取一个分类下的所有视频", notes="获取一个分类下的所有视频", response = VideoEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tid", value = "视频分类id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/type/video_list", method = RequestMethod.GET)
    public JSONResult getVideoListUnderType(@ApiIgnore HttpServletRequest request){
        String obj = request.getParameter("tid");
        int id = NumberUtils.toInt(obj, -1);
        if (id < 0){
            return JSONResult.newBuilder().setStatus(ActionStatus.PARAMAS_ERROR.inValue())
                    .setDesc("tid error").build();
        }
        ArrayList<VideoEntity> videoEntities = videoRepository.findByTidOrderByIsTopDescIdAsc(id);
        if (videoEntities != null && videoEntities.size() > 0){
            //过滤掉已经删除的数据
            removeVideo(videoEntities);
            return JSONResult.okResult(videoEntities);
        }

        return JSONResult.NO_RESULT;
    }

    //传入的数据对象一定不能为空
    private void removeVideo(ArrayList<VideoEntity> videoList){
        for (int j = 0; j < videoList.size(); j++) {
            VideoEntity videoEntity = videoList.get(j);
            String status = videoEntity.getStatus();
            if(CommonParams.VideoStauts.DELETE.equals(status)
                    || CommonParams.VideoStauts.SOLD_OUT.equals(status)){
                videoList.remove(videoEntity);
            }
        }
    }

}
